import React, { useState, useEffect } from 'react';
import { InputLabel, FormControl, Select as MuiSelect, SelectProps } from '@mui/material';

interface SelectComponentProps extends Omit<SelectProps, 'open' | 'onOpen' | 'onClose'> {
  label?: string;
  multiple?: boolean;
  pythonparams?: any;
  commands?: any[];
  children?: React.ReactNode;
}

const Select: React.FC<SelectComponentProps> = ({
  id,
  multiple,
  children,
  onChange,
  label,
  value: propValue,
  commands,
  ...otherProps
}) => {
  const [selectOpen, setSelectOpen] = useState(false);
  const [value, setValue] = useState<any>(propValue || '');

  useEffect(() => {
    // Update value when propValue changes
    let processedValue = propValue || '';
    
    if (multiple && processedValue.constructor?.name !== 'Array') {
      // when loading values from a script, we can't allow strings if *multiple* is enabled
      processedValue = [processedValue];
    } else if (!multiple && Array.isArray(processedValue) && processedValue.length === 0) {
      // when *multiple* is disabled, we can't allow arrays
      processedValue = '';
    }
    
    setValue(processedValue);
  }, [propValue, multiple]);

  const handleOpen = (): void => {
    setSelectOpen(true);
  };

  const handleClose = (): void => {
    setSelectOpen(false);
  };

  const handleChange = (event: any, child: React.ReactNode): void => {
    if (onChange) {
      onChange(event, child);
    }
    handleClose();
  };

  return (
    <FormControl variant="filled" fullWidth>
      {label && <InputLabel>{label}</InputLabel>}
      <MuiSelect
        id={id}
        value={value}
        onChange={handleChange}
        multiple={!!multiple}
        open={selectOpen}
        onOpen={handleOpen}
        onClose={handleClose}
        variant="filled"
        {...otherProps}
      >
        {children}
      </MuiSelect>
    </FormControl>
  );
};

export default Select;

